/**
 * @class 该类为了实现dom排序flip动画效果
 * @param {HTMLElement} container 需要实现动画的容器
 * @param {Number} duration 动画持续时间
 * @author Tangminhui 2024/3/29
 */
class Filp {
  constructor(container = null, duration = 0.5) {
    this.container = container;
    this.chlidrens = [...this.container.children];
    this.animationInProgress = false;
    this.duration = duration;
    this.init()
  }

  init() {
    this.chlidrens.forEach((child) => {
      child.addEventListener("transitionend", () => {
        // 在过渡动画结束时执行的操作
        console.log("Transition ended");
        // 这里可以添加任何你想在动画结束时执行的逻辑
        child.style.removeProperty("transition");
      });
    });
  }

  start() {
    /* const { left, top } = this?.node?.getBoundingClientRect();
    this.startPositon = { left, top };
    console.log(this.startPositon); */
    this.chlidrens.forEach((child) => {
      const { left, top } = child.getBoundingClientRect();
      child.$start_positon = {
        left,
        top,
      };
    });
  }

  end() {
    /* const { left, top } = this?.node?.getBoundingClientRect();
    this.endPositon = { left, top };
    console.log(this.endPositon) */
     /* if (this.animationInProgress) return; 
     this.animationInProgress = true; */
     this.chlidrens.forEach((child) => {
      const { left, top } = child.getBoundingClientRect();
      child.$end_positon = {
        left,
        top,
      };
      const flag =
        this.checkMiniChange(left,child.$start_positon.left) &&
        this.checkMiniChange(top,child.$start_positon.top);
      !flag && this.animate(child);
      // 重新记录开始位置
      child.$start_positon = {
        left,
        top,
      };
    });
  }

  animate(child) {
    console.log('动画')
    child.style.transform = `translate(${
      child.$start_positon.left - child.$end_positon.left
    }px, ${child.$start_positon.top - child.$end_positon.top}px)`;
    this.raf(() => {
      child.style.transition = `transform ${this.duration}s`;
      child.style.removeProperty("transform");
    });
  }

  checkMiniChange (current, last, random = 1) {
    const gap = current.toFixed(0) - last.toFixed(0);
    return gap >= (-1 * random )&& gap <= (1 * random);
  }

  raf(callback) {
    requestIdleCallback(() => {
      requestIdleCallback(callback);
    });
  }
}